﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AvansRS.Domain;
using AvansRS.Domain.DataInterface;
using NHibernate;
using NHibernate.Criterion;

namespace AvansRS.Data
{
	public class PersonRepository : BaseRepository<Person>, IPersonRepository
	{
		public IList<Person> FindByPersonType(string type)
		{
			using(ISession session = SessionProvider.GetSession())
			{
				if(String.IsNullOrEmpty(type))
					return session.CreateCriteria(typeof(Person)).List<Person>();
				IList<Person> list = new List<Person>();

				if(type == "D")
				{
					foreach(Docent docent in session.CreateCriteria(typeof(Docent))
						 .List<Docent>())
					{
						list.Add(docent.Person);
					}
				}
				if(type == "S")
				{
					foreach(Student student in session.CreateCriteria(typeof(Student))
						 .List<Student>())
					{
						list.Add(student.Person);
					}
				}

				return list;
			}
		}

     public Person FindByAccountUsername(string username)
     {
         using (ISession session = SessionProvider.GetSession())
         {
             Person person = session.CreateCriteria(typeof(Person))
                 .CreateCriteria("Account")
                 .Add(Expression.Eq("UserName", username))
                .UniqueResult<Person>();

             /*if (person == null)
                 throw new NotFoundException("Person with username " + username + " not found.");*/

             return person;
         }
     }

		public Person FindByEntity(int entityId)
		{
			using(ISession session = SessionProvider.GetSession())
			{
				Person person = session.CreateCriteria(typeof(Person))
					 .CreateCriteria("Entity")
					 .Add(Expression.Eq("ID", entityId))
					.UniqueResult<Person>();
				return person;
			}
		}

		public IList<Person> FindMatchesByAccountUsername(string username)
		{
			using(ISession session = SessionProvider.GetSession())
			{
				IList<Person> list = session.CreateCriteria<Person>()
					 .CreateCriteria("Account")
					 .Add(Expression.Like("UserName", username, MatchMode.Anywhere))
					 .List<Person>();
				return list;
			}
		}
	}
}
